<template>
  <div class="camera-annotation">
    <!-- 添加提醒信息 -->
    <a-alert
      class="annotation-tips"
      type="info"
      show-icon
    >
      <template #message>
        <div>
          <p>1. 点击"标注"可以进入描绘标注检测区域和维护检测配置</p>
          <p>2. 标注框完成后，点击"同步到终端"，将标注信息同步到AI相机</p>
          <p>3. 只有大华设备才能设置,并且是双目设备才需要设置，单目不需要设置。 {{spraycamera.factory !== 'DHUA' ? "【该设备不是大华设备】" : ""}}{{spraycamera.factory === 'DHUA' && !String(spraycamera.softModel).includes('-E2') ? "【该设备不是双目设备】" : ""}}</p>
        </div>
      </template>
    </a-alert>

    <div class="control-panel">
      <div class="tools">
        <a-card
        :bordered='true'
        style="width: 100%"
        :body-style="{ padding: '24px' }">
          <a-form
            ref='detectionConfigFormRef'
            :model='detectionConfigFormModel'
            :label-col='{ md: { span: 10 }, sm: { span: 24 } }'
            :wrapper-col='{ md: { span: 14 }, sm: { span: 24 } }'
             @submit='saveDetectionConfig2Db'
          >
            <a-row :gutter='8'>
              <a-col :md='10' :sm='24' :xs='24'>
                <a-form-item label="检测区域类型:" name="detectionType">
                  <a-select v-model:value="detectionConfigFormModel.detectionType" placeholder="请选择检测区域类型">
                    <a-select-option :value="1">检测牛头或牛身</a-select-option>
                    <a-select-option :value="2">只检测牛头</a-select-option>
                    <a-select-option :value="3">只检测牛身</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md='14' :sm='24' :xs='24'></a-col>
            </a-row>

            <a-row :gutter='8'>
              <a-col :md='10' :sm='24' :xs='24'>
                <a-form-item label="检测敏感度:" name="detectionSensitivity">
                  <a-input v-model:value="detectionConfigFormModel.detectionSensitivity" placeholder="请输入检测敏感度" />
                </a-form-item>
              </a-col>
               <a-col :md='14' :sm='24' :xs='24'></a-col>
            </a-row>

            <a-row :gutter='8'>
              <a-col :md='4' :sm='24' :xs='24'></a-col>
              <a-col :md='10' :sm='24' :xs='24'>
                <a-button type='primary' html-type='submit'  :disabled="spraycamera.factory !== 'DHUA'">
                  保存数据库
                </a-button>
              </a-col>
              <a-col :md='8' :sm='24' :xs='24' />
            </a-row>
          </a-form>
        </a-card>
      </div>
      <div class="tools">
        <a-space>
          <a-button
          @click="captureImageAction"
          :loading="capImageActionLoading"
          >拉取图片</a-button>
          <a-switch
            v-model:checked="isAnnotating"
            checked-children="标注检测区域中"
            un-checked-children="标注检测区域"
            @change="handleAnnotatingChange"
            :disabled="spraycamera.factory !== 'DHUA' || (spraycamera.factory == 'DHUA' && !String(spraycamera.softModel).includes('-E2'))"
          />
          <a-button
            type="primary"
            @click="handleSync"
            :loading="syncRefLoading"
            :disabled="spraycamera.factory !== 'DHUA'"
          >同步检测区域配置到终端</a-button>
          <!-- 未同步提示标签：当 markIsSync 为 'no' 时显示 -->
          <a-tag v-if="detectionForm.markIsSync === 'no'" color="orange">
            提示：检测区域配置未同步到终端
          </a-tag>
          <a-switch
            v-model:checked="autoRefresh"
            checked-children="自动刷新"
            un-checked-children="手动刷新"
            :disabled="isAnnotating"
            @change="handleAutoRefresh"
          />
          <a-button
           type="primary"
            v-if="!autoRefresh"
            @click="handleManualRefresh"
            :loading="refreshLoading"
          >刷新</a-button>

           <a-button
            type="primary"
            @click="handleQueryDetectionMark"
            :loading="queryDetectionMarkLoading"
            :disabled="spraycamera.factory !== 'DHUA'"
          >从终端查询检测相关配置</a-button>
        
          <a-button
            type="primary"
            @click="syncDetectionToSomeOxtall"
            :disabled="spraycamera.factory !== 'DHUA'"
          >一键同步到同牛舍下双目设备</a-button>
        </a-space>
      </div>

      <!-- 新增清晰度和缩放比例控制行 -->
      <div class="image-controls">
        <a-space>
          <span>刷新过程中是否拉取图片:</span>
          <a-switch
            v-model:checked="autoCapture"
            checked-children="是"
            un-checked-children="否"
          />
          <span>清晰度:</span>
          <a-select v-model:value="clarityLevel" style="width: 90px" @change="handleClarityChange">
            <a-select-option value="20">20%</a-select-option>
            <a-select-option value="30">30%</a-select-option>
            <a-select-option value="40">40%</a-select-option>
            <a-select-option value="50">50%</a-select-option>
          </a-select>

          <span>缩放比例:</span>
          <a-select v-model:value="zoomLevel" style="width: 90px" @change="handleZoomChange">
            <a-select-option value="20">20%</a-select-option>
            <a-select-option value="30">30%</a-select-option>
            <a-select-option value="40">40%</a-select-option>
            <a-select-option value="50">50%</a-select-option>
          </a-select>
          <span>是否携带标注标位:</span>
          <a-select v-model:value="withAnnotation" style="width: 60px">
            <a-select-option value="0">否</a-select-option>
            <a-select-option value="1">是</a-select-option>
          </a-select>
          <span>是否携带识别检测结果:</span>
          <a-select v-model:value="withDetection" style="width: 60px">
            <a-select-option value="0">否</a-select-option>
            <a-select-option value="1">是</a-select-option>
          </a-select>
          <span>是否携带时间:</span>
          <a-select v-model:value="withTimestamp" style="width: 60px">
            <a-select-option value="0">否</a-select-option>
            <a-select-option value="1">是</a-select-option>
          </a-select>
        </a-space>
      </div>
    </div>

    <div class="canvas-container">
      <canvas
        ref="canvas"
        @mousedown="startDrawing"
        @mousemove="drawing"
        @mouseup="endDrawing"
      ></canvas>
    </div>

    <!-- 添加设备信息输入弹窗 -->
    <!-- 修改设备信息弹窗 -->
    <a-modal
      v-model:visible="deviceModalVisible"
      :title="isEditing ? '编辑检测区域' : '添加检测区域'"
      @ok="handleDeviceSubmit"
      @cancel="handleDeviceCancel"
    >
      <template #footer>
        <a-button key="back" @click="handleDeviceCancel">取消</a-button>
        <a-button v-if="isEditing" key="delete" danger @click="handleDeviceDelete">
          删除
        </a-button>
        <a-button key="submit" type="primary" @click="handleDeviceSubmit">
          确定
        </a-button>
      </template>
    </a-modal>


  </div>
</template>

<script>
import { message } from 'ant-design-vue'
import {DeviceSprayCameraCaptureimgApi} from "@/api/property/spraycamera/DeviceSprayCameraCaptureimgApi";
import {DeviceSprayCameraSlotApi} from "@/api/property/spraycamera/DeviceSprayCameraSlotApi";
import {DeviceCommandDownQueueApi} from "@/api/property/DeviceCommandDownQueueApi";
import {DeviceSprayCameraApi} from "@/api/property/spraycamera/DeviceSprayCameraApi";
import {DeviceSprayCameraStaticConfigApi} from "@/api/property/spraycamera/DeviceSprayCameraStaticConfigApi";
import {DeviceCommandTemplateDistributeApi} from "@/api/property/DeviceCommandTemplateDistributeApi";
export default {
  name: 'DeviceSpraycameraDrawing',
  components: {
  },
  props: {
    data: Object
  },
  data() {
    return {
      spraycamera : {},
      canvas: null,
      ctx: null,
      isDrawing: false,
      startPoint: { x: 0, y: 0 },
      currentMode: 'rectangle',
      autoRefresh: false,
      selectedBox: null,
      annotations: [],
      refreshInterval: null,
      // 添加新的数据项
      deviceModalVisible: false,
      deviceForm: {
        relayid: '',
      },
      tempAnnotation: null, // 临时存储当前绘制的标注
      originalImage: null, // 存储原始图片
      isAnnotating: false, // 是否处于标注状态
      isEditing: false, // 是否处于编辑状态
      previousAutoRefresh: false, // 保存标注前的自动刷新状态
      selectedAnnotation: null, // 当前选中的标注
      // 提交状态
      loading: false,
      refreshLoading: false, // 添加刷新按钮的 loading 状态
      syncRefLoading : false,
      syncRefTimer : false,

      capImageActionLoading: false, // 添加刷新按钮的 loading 状态
      capImageActionRefTimer : false,

      // 新增图像控制相关数据
      clarityLevel: '50',
      zoomLevel: '50',
      autoCapture: false, // 是否自动拉取图片
       // 新增三个选项
       withAnnotation: '1',
      withDetection: '1',
      withTimestamp: '0',
      ORIGINAL_WIDTH: 1920,  // 1080P 宽度
      ORIGINAL_HEIGHT: 1080, // 1080P 高度
      displayScale: 1,       // 当前显示比例
      detectionForm: {
        detectionMark: [], // 检测区域矩形（单个），格式为 [[x1,y1],[x2,y2],[x3,y3],[x4,y4]],
        markIsSync : '',
      },

      detectionConfigFormModel : {
        detectionType : 1,
        detectionSensitivity : 0
      },
      
      queryDetectionMarkLoading: false, // 添加查询按钮的 loading 状态
      queryDetectionMarkTimer : false,
    }
  },

  async mounted() {
    let that = this;
    // 先获取相机详情，包括factory信息
    const cameraResult = await DeviceSprayCameraApi.detailByRecord(this.data.recordId);
    console.log('相机信息:', cameraResult);
    this.spraycamera = cameraResult || {};

    this.getStaticConfig();
    
    // 初始化画布，但不设置固定大小
    const canvasEl = this.$refs.canvas
    this.canvas = canvasEl
    this.ctx = canvasEl.getContext('2d')

    // 默认开启自动刷新
    this.autoRefresh = true
    this.handleAutoRefresh(true)

    this.loadImage()
    this.loadAnnotations() // 添加初始加载
  },

  unmounted() {
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval)
    }
  },

  methods: {
    async getStaticConfig() {
      const staticConfigResult = await DeviceSprayCameraStaticConfigApi.detail({"recordId": this.data.recordId});
      console.log('静态配置信息:', staticConfigResult);
      if (staticConfigResult) {
        let detectionMarkJson = Object.assign({}, (staticConfigResult.detectionMark ? (JSON.parse(staticConfigResult.detectionMark) || {}) : {}));
        this.detectionForm.detectionMark = detectionMarkJson.point || [];
        this.detectionForm.markIsSync = detectionMarkJson.markIsSync || '';
        
        this.detectionConfigFormModel.detectionType = staticConfigResult.detectionType || 1;
        this.detectionConfigFormModel.detectionSensitivity = staticConfigResult.detectionSensitivity || 0;
      }
    },

    async handleManualRefresh() {
      try {
        this.refreshLoading = true
        if (this.autoCapture) {
          await this.captureImageSync(); // 如果开启了自动拉取，则先拉取图片
        }
        await this.loadImage()
        await this.loadAnnotations()
        message.success('刷新成功')
      } catch (error) {
        message.error('刷新失败')
      } finally {
        this.refreshLoading = false
      }
    },

    handleAutoRefresh(value) {
      if (value) {
        this.refreshInterval = setInterval(() => {
          if (this.autoCapture) {
            this.captureImageSync(); // 如果开启了自动拉取，则先拉取图片
          }
          this.loadImage()
          this.loadAnnotations()
        }, 5000)
      } else {
        clearInterval(this.refreshInterval)
      }
    },

    handleAnnotatingChange(value) {
      if (value) {
        // 进入标注状态
        this.previousAutoRefresh = this.autoRefresh
        if (this.autoRefresh) {
          this.autoRefresh = false
          clearInterval(this.refreshInterval)
        }
      } else {
        // 退出标注状态
        this.autoRefresh = this.previousAutoRefresh
        if (this.previousAutoRefresh) {
          this.handleAutoRefresh(true)
        }
      }
    },

    async captureImageSync() {
      let updateDataRecord = {
        updateData: JSON.stringify({
          old: '',
          update: {
            config : {
              scale : this.zoomLevel,
              quality : this.clarityLevel,
              marks: this.withAnnotation,
              check: this.withDetection,
              time: this.withTimestamp
            }
          }
        }),
        recordId: this.data.recordId,
        templateCode: 'spraycamera',
        dictate : 7,
        sceneDictate : 7
      };
      let result = DeviceCommandDownQueueApi.add2(updateDataRecord);
      result
        .then(result => {

        })
        .catch(errorMsg => {
          message.error(errorMsg)
        });
    },

    // 修改 loadImage 方法，保存原始图片
    async loadImage() {
      try {
        if (!this.ctx || !this.canvas) {
          this.canvas = this.$refs.canvas
          this.ctx = this.canvas.getContext('2d', {
            alpha: true  // 确保支持透明度
          })
        }
        let lastOne = await DeviceSprayCameraCaptureimgApi.findLastOne(this.data.recordId);
        let imageData = lastOne.data.imgUrl ? lastOne.data.imgUrl : 'https://moreycow.oss-cn-hangzhou.aliyuncs.com/vechile/icon/4c4a5be84e8b7ffe35a4192b834f6d2e.jpg';
        const img = new Image()

        img.onload = () => {
          // 计算当前图片相对于1080P的缩放比例,如果是大华的相机，就一直保持不变
          if (this.spraycamera && this.spraycamera.factory === 'DHUA') {
            this.displayScale = 1;
          } else {
            this.displayScale = img.width / this.ORIGINAL_WIDTH;
          }
         
          // 使用图片原始尺寸
          this.canvas.width = img.width
          this.canvas.height = img.height
          this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
          this.ctx.drawImage(img, 0, 0, img.width, img.height)
          this.originalImage = img
          if (this.annotations.length > 0) {
            this.drawAnnotations()
          }
        }

        img.onerror = () => {
          message.error('图片加载失败')
        }

        img.src = imageData
      } catch (error) {
        message.error('加载图片失败')
      }
    },

    async loadAnnotations() {
      try {
        let slotList = [];
        let list = await DeviceSprayCameraSlotApi.list({"recordId" : this.data.recordId});
        console.log(list);
        if (list.data && list.data.length > 0) { 
          console.log(list);
          list.data.forEach(function (item) {
            let pointObj = JSON.parse(item.point) || {};
            let formatItem = {
              points : pointObj.points,
              type : pointObj.type,
              x: pointObj.x,
              y: pointObj.y,
              width: pointObj.width,
              height: pointObj.height,
              relayid : item.relayid,
              relaySwitch : item.wifirelayDTO ? item.wifirelayDTO.relaySwitch : 1,
              relaySwitchText : '',
              status : item.wifirelayDTO ? item.wifirelayDTO.status : 1,
              statusText : "",
              scsId : item.scsId,
              link : item.wifirelayDTO? item.wifirelayDTO.link : 1,
              linkText : ""
            };

            if (item.wifirelayDTO && item.wifirelayDTO.link == 2) {
              formatItem.linkText = "已连";
            } else if (item.wifirelayDTO && item.wifirelayDTO.link == 1) {
              formatItem.linkText = "断连";
            } else {
              formatItem.linkText = "未知状态";
            }

            if (item.wifirelayDTO && item.wifirelayDTO.relaySwitch == 1) {
              formatItem.relaySwitchText = "喷淋关闭";
            } else if (item.wifirelayDTO && item.wifirelayDTO.relaySwitch == 2) {
              formatItem.relaySwitchText = "喷淋开启";
            } else if (item.wifirelayDTO && item.wifirelayDTO.relaySwitch == 3) {
              formatItem.relaySwitchText = "等待喷淋";
            } else if (item.wifirelayDTO && item.wifirelayDTO.relaySwitch == 4) {
              formatItem.relaySwitchText = "喷淋失败";
            } else {
              formatItem.relaySwitchText = "未知状态";
            }
              
            if (item.wifirelayDTO && item.wifirelayDTO.status == 1) {
              formatItem.statusText = "未识别";
            } else if (item.wifirelayDTO && item.wifirelayDTO.status == 2) {
              formatItem.statusText = "识别到牛";
            } else {
              formatItem.statusText = "未识别";
            }

            slotList.push(formatItem);
          })
        }
        console.log(slotList);
        // 模拟从服务器获取的数据
        this.annotations = slotList;

        //   [
        //   {
        //     points: [[100, 100], [100, 200], [200, 200], [200, 100]],
        //     deviceType: 'camera',
        //     deviceName: '摄像头1',
        //     remark: '主入口监控',
        //     type: 'rectangle',
        //     x: 100,
        //     y: 100,
        //     width: 100,
        //     height: 100
        //   }
        // ]
        this.drawAnnotations()
      } catch (error) {
        message.error('加载标注数据失败')
      }
    },

    drawAnnotations() {
      this.annotations.forEach(annotation => {
        this.drawBox(annotation)
      })
      // 绘制检测区域
      this.drawDetectionMarks()
    },

    calculateSize(points) {
      if (!points || points.length < 4) {
        return '0 x 0'
      }
      const width = Math.abs(points[3][0] - points[0][0])
      const height = Math.abs(points[1][1] - points[0][1])
      return `${Math.round(width)} x ${Math.round(height)}`
    },

    drawBox(box) {
      if (!this.ctx) return

      this.ctx.beginPath()
      // 根据连接状态设置边框颜色
      this.ctx.strokeStyle = box.link === 2 ? '#52c41a' : '#FF4D4F' // 断连红色，已连绿色
      this.ctx.lineWidth = 2

      if (box.points && box.points.length === 4) {
        // 将1080P坐标转换为当前显示坐标
        let displayPoints;
        if (this.spraycamera && this.spraycamera.factory === 'DHUA') {
          // 大华相机：从8192范围转换为像素坐标
          displayPoints = box.points.map(point => [
            // 从8192范围转换回像素坐标
            (point[0] * this.canvas.width) / 8192,
            (point[1] * this.canvas.height) / 8192
          ]);
        } else {
          // 普通相机：将1080P坐标转换为当前显示坐标
          displayPoints = box.points.map(point => [
            point[0] * this.displayScale,
            point[1] * this.displayScale
          ]);
        }
        const points = displayPoints;
        // 计算标注框宽度
        const boxWidth = Math.abs(points[3][0] - points[0][0])

        // 绘制矩形框
        this.ctx.moveTo(points[0][0], points[0][1])
        for (let i = 1; i < points.length; i++) {
          this.ctx.lineTo(points[i][0], points[i][1])
        }
        this.ctx.lineTo(points[0][0], points[0][1])
        this.ctx.stroke()

        // 第一行：设备ID
        this.ctx.fillStyle = 'rgba(24, 144, 255, 0.2)'
        this.ctx.fillRect(points[0][0], points[0][1] - 80, boxWidth, 20)
        this.ctx.fillStyle = '#fff'
        this.ctx.font = '12px Arial'
        this.ctx.fillText(
          `${box.relayid}`,
          points[0][0] + 5,
          points[0][1] - 65
        )

        // 第二行：连接状态
        this.ctx.fillStyle = box.link === 2 ? 'rgba(82, 196, 26, 0.2)' : 'rgba(255, 77, 79, 0.2)'
        this.ctx.fillRect(points[0][0], points[0][1] - 60, boxWidth, 20)
        this.ctx.fillStyle = '#fff'
        this.ctx.fillText(
          box.link === 2 ? "已连" : "断连",
          points[0][0] + 5,
          points[0][1] - 45
        )

        // 第三行：喷淋状态
        let sprayColor;
        switch (box.relaySwitch) {
          case 1:
            sprayColor = 'rgba(255, 77, 79, 0.2)';  // 喷淋关闭 - 红色
            break;
          case 2:
            sprayColor = 'rgba(82, 196, 26, 0.2)';  // 喷淋开启 - 绿色
            break;
          case 3:
            sprayColor = 'rgba(250, 173, 20, 0.2)';  // 喷淋等待 - 黄色
            break;
          case 4:
            sprayColor = 'rgba(255, 77, 79, 0.2)';  // 喷淋失败 - 红色
            break;
          default:
            sprayColor = 'rgba(217, 217, 217, 0.2)';  // 未知状态 - 灰色
        }
        this.ctx.fillStyle = sprayColor
        this.ctx.fillRect(points[0][0], points[0][1] - 40, boxWidth, 20)
        this.ctx.fillStyle = '#fff'
        this.ctx.fillText(
          `${box.relaySwitchText}`,
          points[0][0] + 5,
          points[0][1] - 25
        )


        // 第四行：识别状态
        this.ctx.fillStyle = box.status === 2 ? 'rgba(82, 196, 26, 0.2)' : 'rgba(255, 77, 79, 0.2)'
        this.ctx.fillRect(points[0][0], points[0][1] - 20, boxWidth, 20)
        this.ctx.fillStyle = '#fff'
        this.ctx.fillText(
          `${box.statusText}`,
          points[0][0] + 5,
          points[0][1] - 5
        )
      }
    },

    // 绘制检测区域（detectionMarks）
    drawDetectionMarks() {
      if (!this.ctx) return
      const dm = this.detectionForm.detectionMark
      if (!dm || !Array.isArray(dm) || dm.length !== 4) return

      // 将坐标转换为当前显示坐标
      let points
      if (this.spraycamera && this.spraycamera.factory === 'DHUA') {
        points = dm.map(point => [
          (point[0] * this.canvas.width) / 8192,
          (point[1] * this.canvas.height) / 8192
        ])
      } else {
        points = dm.map(point => [
          point[0] * this.displayScale,
          point[1] * this.displayScale
        ])
      }

      const boxWidth = Math.abs(points[3][0] - points[0][0])

      this.ctx.beginPath()
      this.ctx.strokeStyle = '#FF4D4F' // 大红色表示检测区域
      this.ctx.lineWidth = 2
      this.ctx.moveTo(points[0][0], points[0][1])
      for (let i = 1; i < points.length; i++) {
        this.ctx.lineTo(points[i][0], points[i][1])
      }
      this.ctx.lineTo(points[0][0], points[0][1])
      this.ctx.stroke()

      // 标签：检测区域
      this.ctx.fillStyle = 'rgba(82, 196, 26, 0.2)'
      this.ctx.fillRect(points[0][0], points[0][1] - 20, boxWidth, 20)
      this.ctx.fillStyle = '#fff'
      this.ctx.font = '12px Arial'
      this.ctx.fillText('检测区域', points[0][0] + 5, points[0][1] - 5)
    },


    startDrawing(e) {
      const rect = this.$refs.canvas.getBoundingClientRect()
      const x = e.clientX - rect.left
      const y = e.clientY - rect.top

      // 检查是否点击了已有标注
      const clickedDetectionMark = this.findClickedDetectionMark(x, y)
      console.log(this.isAnnotating)
      if (this.isAnnotating) {
        if (clickedDetectionMark) {
          console.log(clickedDetectionMark);
          // 标注状态下点击已有标注，进入编辑模式
          this.selectedDetectionMark = clickedDetectionMark
          this.isEditing = true
          this.deviceModalVisible = true
          return
        }

        // 若已有检测区域（point不为空），不允许新增第二条
        const hasDetection = Array.isArray(this.detectionForm.detectionMark) && this.detectionForm.detectionMark.length === 4
        if (hasDetection) {
          message.warning('已存在检测区域，无法添加第二条')
          return
        }

        // 标注状态下点击空白区域，开始绘制新标注
        this.isDrawing = true
        this.startPoint = { x, y }
      }
      // 非标注状态下，不做任何响应
    },

    findClickedDetectionMark(x, y) {
      console.log(x, y);
      const dm = this.detectionForm.detectionMark;
      console.log(dm);
      if (!dm || !Array.isArray(dm) || dm.length !== 4) {
        return null;
      }

      // 将坐标转换为当前显示坐标
      let displayPoints;
      if (this.spraycamera && this.spraycamera.factory === 'DHUA') {
        // 大华相机：从8192范围转换为像素坐标
        displayPoints = dm.map(point => [
          (point[0] * this.canvas.width) / 8192,
          (point[1] * this.canvas.height) / 8192
        ]);
      } else {
        // 普通相机：将1080P坐标转换为当前显示坐标
        displayPoints = dm.map(point => [
          point[0] * this.displayScale,
          point[1] * this.displayScale
        ]);
      }

      const hit = (
        x >= displayPoints[0][0] &&
        x <= displayPoints[2][0] &&
        y >= displayPoints[0][1] &&
        y <= displayPoints[2][1]
      );
      console.log(hit);

      return hit ? dm : null;
    },

    // 修改 drawing 方法，避免多重绘制
    drawing(e) {
      if (!this.isDrawing) return

      const rect = this.$refs.canvas.getBoundingClientRect()
      const currentX = e.clientX - rect.left
      const currentY = e.clientY - rect.top

      // 重新绘制原始图片和已有标注
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
      this.ctx.drawImage(this.originalImage, 0, 0, this.canvas.width, this.canvas.height)
      this.drawAnnotations()

      // 绘制当前框
      let width = currentX - this.startPoint.x
      let height = currentY - this.startPoint.y

      this.ctx.beginPath()
      this.ctx.strokeStyle = '#FF4D4F' // 大红色表示检测区域
      this.ctx.lineWidth = 2
      this.ctx.strokeRect(
        this.startPoint.x,
        this.startPoint.y,
        width,
        height
      )
    },

    // 添加坐标转换方法
    convertToOriginalCoordinate(x, y) {
      // 将当前坐标转换为1080P对应的坐标
      return {
        x: Math.round(x / this.displayScale),
        y: Math.round(y / this.displayScale)
      };
    },

    // 添加DHUA相机坐标转换方法
    convertToDHUACoordinate(x, y, width, height) {
      // 将像素坐标转换为8192范围
      return {
        x: Math.round(x / width * 8192),
        y: Math.round(y / height * 8192)
      };
    },

    // 修改 endDrawing 方法，添加弹窗逻辑
    endDrawing(e) {
      if (!this.isDrawing) return

      this.isDrawing = false
      const rect = this.$refs.canvas.getBoundingClientRect()
      const endX = e.clientX - rect.left
      const endY = e.clientY - rect.top

      let width = endX - this.startPoint.x
      let height = endY - this.startPoint.y

      // 如果绘制的框太小，则不创建标注
      if (Math.abs(width) < 20 || Math.abs(height) < 20) {
        // 重新绘制画布，清除临时绘制的框
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
        this.ctx.drawImage(this.originalImage, 0, 0, this.canvas.width, this.canvas.height)
        this.drawAnnotations()
        return
      }

      // 根据相机类型进行不同的坐标转换
      if (this.spraycamera && this.spraycamera.factory === 'DHUA') {
        // 大华相机：转换为8192范围的坐标
        const startDHUA = this.convertToDHUACoordinate(this.startPoint.x, this.startPoint.y, this.canvas.width, this.canvas.height);
        const endDHUA = this.convertToDHUACoordinate(endX, endY, this.canvas.width, this.canvas.height);
        const dhuaWidth = Math.abs(endDHUA.x - startDHUA.x);
        const dhuaHeight = Math.abs(endDHUA.y - startDHUA.y);

        // 确保坐标和尺寸为整数
        this.tempDetectionMark = [
          //左上角
          [startDHUA.x, startDHUA.y],
          //左下角
          [startDHUA.x, startDHUA.y + dhuaHeight],
          //右下角
          [startDHUA.x + dhuaWidth, startDHUA.y + dhuaHeight],
          //右上角
          [startDHUA.x + dhuaWidth, startDHUA.y]
        ]
      } else {
        // 普通相机：转换为1080P坐标
        const startCoord = this.convertToOriginalCoordinate(this.startPoint.x, this.startPoint.y);
        const endCoord = this.convertToOriginalCoordinate(endX, endY);
        const originalWidth = Math.abs(endCoord.x - startCoord.x);
        const originalHeight = Math.abs(endCoord.y - startCoord.y);

        this.tempDetectionMark = [
          //左上角
          [startCoord.x, startCoord.y],
          //左下角
          [startCoord.x, startCoord.y + originalHeight],
          //右下角
          [startCoord.x + originalWidth, startCoord.y + originalHeight],
          //右上角
          [startCoord.x + originalWidth, startCoord.y]
        ]
      }

      // 确保新建标注时使用空的表单数据
      this.isEditing = false;
      this.selectedDetectionMark = null;
      // 显示设备信息输入弹窗
      this.deviceModalVisible = true
    },

    // 添加设备信息提交方法
    async handleDeviceSubmit() {
      try {
        let that = this;
        this.loading = true;
        let result = null;
        // 执行编辑或修改
        let pointJsonObj = {
          point : this.tempDetectionMark,
          markIsSync : 'no'
        };
        if (this.isEditing) {
          // 编辑模式
          pointJsonObj.point = this.selectedDetectionMark;
        }
        let updateForm = {
          detectionMark : JSON.stringify(pointJsonObj),
          recordId : this.data.recordId
        }
        result = DeviceSprayCameraStaticConfigApi.edit(updateForm);
        result
          .then(result => {
            // 移除加载框
            that.loading = false;

            // 提示添加成功
            message.success(result.message);

            that.deviceModalVisible = false
            that.tempDetectionMark = null
            that.selectedDetectionMark = null
            that.isEditing = false

            that.getStaticConfig().then(() => {
              // 从服务器重新加载数据
              that.loadImage()
              that.loadAnnotations()
            });

          })
          .catch(() => {
            message.error('保存失败')
            that.loading = false;
          });
      } catch (error) {
        message.error('保存失败')
      }
    },

    async handleDeviceDelete() {
      try {
        if (!this.selectedDetectionMark) return;
        let that = this;
        this.loading = true;
        let pointJsonObj = {
          point : [],
          markIsSync : 'no'
        };
        let updateForm = {
          detectionMark : JSON.stringify(pointJsonObj),
          recordId : this.data.recordId
        }
        let result = DeviceSprayCameraStaticConfigApi.edit(updateForm);
        result
          .then(result => {
            // 移除加载框
            that.loading = false;

            // 提示添加成功
            message.success('删除成功');

            // 从本地列表中移除
            that.deviceModalVisible = false
            that.selectedDetectionMark = null
            that.isEditing = false

            that.getStaticConfig().then(() => {
              // 从服务器重新加载数据
              that.loadImage()
              that.loadAnnotations()
            });
          })
          .catch(() => {
            message.error('删除失败')
            that.loading = false;
          });
      } catch (error) {
        message.error('删除失败')
      }
    },

    // 添加取消方法
    handleDeviceCancel() {
      this.deviceModalVisible = false
      this.tempAnnotation = null
      this.selectedAnnotation = null
      this.isEditing = false

      // 重新绘制
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
      this.ctx.drawImage(this.originalImage, 0, 0, this.canvas.width, this.canvas.height)
      this.drawAnnotations()
    },


    checkProcess(sceneDictate, clearCallback, callback) {
      let params = {
        recordId: this.data.recordId,
        sceneDictate: sceneDictate
      };
      let result = DeviceCommandDownQueueApi.workingDetail(params);
      result
        .then(result => {
          if (!result || !result.dcdqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },

    //查询wifi继电器 begin
    clearSyncRef(){
      this.syncRefLoading = false;
      clearInterval(this.syncRefTimer);
    },
    checkSync(){
      let that = this;
      this.checkProcess(18, this.clearSyncRef, function(){
        that.getStaticConfig().then(() => {
          // 从服务器重新加载数据
          that.loadImage()
          that.loadAnnotations()
        });
      });
    },
    handleSync()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 18
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushSyncCmd();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushSyncCmd() {
      this.loading = true;
      let updateDataRecord = {
        updateData: JSON.stringify({
          old: '',
          update: ''
        }),
        recordId: this.data.recordId,
        templateCode: 'spraycamera',
        dictate : 18,
        sceneDictate : 18
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.syncRefLoading = true; //转圈
          this.syncRefTimer = setInterval(this.checkSync, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //查询wifi继电器 end

    //查询图片begin
    clearCapImageActionRef(){
      this.capImageActionLoading = false;
      clearInterval(this.capImageActionRefTimer);
    },
    checkCapImageAction(){
      this.checkProcess(7, this.clearCapImageActionRef, function(){

      });
    },
    captureImageAction()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 7
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushCaptureImageAction();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushCaptureImageAction() {
      this.loading = true;
      let updateDataRecord = {
        updateData: JSON.stringify({
          old: '',
          update: {
            config : {
              scale : this.zoomLevel,
              quality : this.clarityLevel,
              marks: this.withAnnotation,
              check: this.withDetection,
              time: this.withTimestamp
            }
          }
        }),
        recordId: this.data.recordId,
        templateCode: 'spraycamera',
        dictate : 7,
        sceneDictate : 7
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.capImageActionLoading = true; //转圈
          this.capImageActionRefTimer = setInterval(this.checkCapImageAction, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //查询图片end

    //查询检测区域配置 begin
    clearQueryDetectionMarkRef(){
      this.queryDetectionMarkLoading = false;
      clearInterval(this.queryDetectionMarkTimer);
    },
    checkQueryDetectionMark(){
      let that = this;
      this.checkProcess(19, this.clearQueryDetectionMarkRef, function(){
        that.getStaticConfig().then(() => {
          // 从服务器重新加载数据
          that.loadImage()
          that.loadAnnotations()
        });
      });
    },
    handleQueryDetectionMark()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 19
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushQueryDetectionMark();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushQueryDetectionMark() {
      this.loading = true;
      let updateDataRecord = {
        updateData: JSON.stringify({
          old: '',
          update: ''
        }),
        recordId: this.data.recordId,
        templateCode: 'spraycamera',
        dictate : 19,
        sceneDictate : 19
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.queryDetectionMarkLoading = true; //转圈
          this.queryDetectionMarkTimer = setInterval(this.checkQueryDetectionMark, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },

    //查询检测区域配置 end





    handleClarityChange(value) {
      this.clarityLevel = value;
      // 这里可以添加清晰度调整的逻辑
      console.log('清晰度设置为:', value);
      // 可以在这里调用API或者更新图像
    },

    // 处理缩放比例变化
    handleZoomChange(value) {
      this.zoomLevel = value;
      // 这里可以添加缩放比例调整的逻辑
      console.log('缩放比例设置为:', value);
      // 可以在这里调整画布大小或者图像显示
    },


    syncDetectionToSomeOxtall() {
      if (this.data.oxtId <= 0) {
        message.error('当前牛舍没有其他牛舍');
        return;
      }
      let that = this;
      this.loading = true;
      // 格式化时间段数据为JSON字符串
      let toObjs = {
        "oxtall_ids" : [that.data.oxtId]
      };
      let addParams = {
        "templateCode" : "spraycamera",
        "toObjs" : JSON.stringify(toObjs),
        "sceneDictate" : 18,
        "dictate" : 18,
        "templateContent" : JSON.stringify({
          ...that.detectionForm,
          ...that.detectionConfigFormModel
        })
      };
      let result2 = DeviceCommandTemplateDistributeApi.add(addParams);
      result2.then(res => {
        // 移除加载框
        that.loading = false;
        // 提示添加成功
        message.success(res.message);
      })
        .catch(() => {
          that.loading = false;
        });
    },

    saveDetectionConfig2Db() {
      try {
        let that = this;
        this.loading = true;
        let result = null;
        // 执行编辑或修改
        let pointJsonObj = {
          point : this.detectionForm.detectionMark,
          markIsSync : 'no'
        };
        let updateForm = {
          detectionMark : JSON.stringify(pointJsonObj),
          detectionType : this.detectionConfigFormModel.detectionType,
          detectionSensitivity : this.detectionConfigFormModel.detectionSensitivity,
          recordId : this.data.recordId
        }
        result = DeviceSprayCameraStaticConfigApi.edit(updateForm);
        result
          .then(result => {
            // 移除加载框
            that.loading = false;

            // 提示添加成功
            message.success(result.message);
            that.getStaticConfig().then(() => {
              // 从服务器重新加载数据
              that.loadImage()
              that.loadAnnotations()
            });

          })
          .catch(() => {
            message.error('保存失败')
            that.loading = false;
          });
      } catch (error) {
        message.error('保存失败')
      }
    },
    

  


    

  }
}
</script>

<style scoped>
.camera-annotation {
  padding: 24px;
}

.annotation-tips {
  margin-bottom: 16px;
}

.annotation-tips :deep(p) {
  margin-bottom: 4px;
}

.annotation-tips :deep(p:last-child) {
  margin-bottom: 0;
}

.control-panel {
  margin-bottom: 24px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.tools {
  margin-bottom: 16px;
  width: 100%;
}

.image-controls {
  margin-bottom: 16px;
  width: 100%;
}

.canvas-container {
  border: 1px solid #f0f0f0;
  display: inline-block;
  border-radius: 2px;
}

canvas {
  background-color: #fafafa;
}

.coordinates {
  width: 300px;
  margin-left: 16px;
}

.coordinates p {
  margin-bottom: 8px;
}

:deep(.ant-card-body) {
  padding: 24px;
}
</style>
